package cn.com.aiton.educenter.controller;


import cn.com.aiton.educenter.client.DictionaryClient;
import cn.com.aiton.educenter.config.OperLog;
import cn.com.aiton.educenter.entity.PestsControl;
import cn.com.aiton.educenter.entity.UcenterMember;
import cn.com.aiton.educenter.entity.vo.PestsControlVo;

import cn.com.aiton.educenter.entity.vo.PestsQrcodeVo;
import cn.com.aiton.educenter.service.PestsQrcodeService;
import cn.com.aiton.educenter.service.UcenterMemberService;
import cn.com.qiter.common.Result;
import cn.com.qiter.common.vo.PestsControlModel;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.com.aiton.educenter.entity.vo.PestsControlQuery;
import cn.com.aiton.educenter.service.PestsControlService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 防治业务数据表 前端控制器
 * </p>
 *
 * @author q
 * @since 2021-01-29
 */
@Log4j2
@RestController
@RequestMapping("/educenter/pests")
public class PestsControlController {
    //把service注入
    @Autowired
    private PestsControlService pestsControlService;

    @Autowired
    private DictionaryClient dictionaryClient;
    @Autowired
    private PestsQrcodeService pestsQrcodeService;
    @Autowired
    private UcenterMemberService ucenterMemberService;
    //1 查询讲师表所有数据
    //rest风格
    @ApiOperation(value = "所有防治列表")
    @GetMapping("findAll")
    @OperLog(type = "查询",module = "PestsControlController",requestDes = "所有防治列表")
    public Result findAll() {
        //调用service的方法实现查询所有的操作
        List<PestsControl> list = pestsControlService.list(null);
        return Result.ok().data("items",list);
    }

    //2 逻辑删除讲师的方法
    @ApiOperation(value = "逻辑删除防治")
    @DeleteMapping("removeControl/{id}")
    @OperLog(type = "删除",module = "PestsControlController",requestDes = "逻辑删除防治")
    public Result removeControl(@ApiParam(name = "id", value = "ID", required = true)
                           @PathVariable String id) {
        boolean flag = pestsControlService.removeById(id);
        if(flag) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }

    //3 分页查询防治的方法
    //current 当前页
    //limit 每页记录数
    @ApiOperation(value = "分页查询")
    @GetMapping("pageControl/{current}/{limit}")
    @OperLog(type = "分页查询",module = "PestsControlController",requestDes = "分页查询防治的方法")
    public Result pageControl(@PathVariable long current,
                                                 @PathVariable long limit) {
        //创建page对象
        Page<PestsControl> pageTeacher = new Page<>(current,limit);

        //调用方法实现分页
        //调用方法时候，底层封装，把分页所有数据封装到pageTeacher对象里面
        pestsControlService.page(pageTeacher,null);
        long total = pageTeacher.getTotal();//总记录数
        List<PestsControl> records = pageTeacher.getRecords(); //数据list集合

        return Result.ok().data("total",total).data("rows",records);
    }


    //4 条件查询带分页的方法
    @ApiOperation(value = "分页查询")
    @OperLog(type = "分页查询",module = "PestsControlController",requestDes = "分页查询防治的方法")
    @PostMapping("page/{current}/{limit}")
    public Result page(@PathVariable long current, @PathVariable long limit,
                                       @RequestBody(required = false) PestsControlQuery teacherQuery) {
        //创建page对象
        Page<PestsControl> pageTeacher = new Page<>(current,limit);

        //构建条件
        QueryWrapper<PestsControl> wrapper = new QueryWrapper<>();
        // 多条件组合查询
        // mybatis学过 动态sql
        String deviceId = teacherQuery.getDeviceId();
        String begin = teacherQuery.getBegin();
        String end = teacherQuery.getEnd();
        String pestsType = teacherQuery.getPestsType();
        String projectId = teacherQuery.getProjectId();
        String userId = teacherQuery.getUserId();
        //判断条件值是否为空，如果不为空拼接条件
        if(!StringUtils.isEmpty(deviceId)) {
            //构建条件
            wrapper.like("device_id",deviceId);
        }
        if(!StringUtils.isEmpty(begin)) {
            wrapper.ge("stime",begin);
        }
        if(!StringUtils.isEmpty(end)) {
            wrapper.le("stime",end);
        }

        if(!StringUtils.isEmpty(userId)) {
            wrapper.eq("user_id",userId);
        }
        if(!StringUtils.isEmpty(projectId)) {
            wrapper.eq("project_id",projectId);
        }
        if(!StringUtils.isEmpty(pestsType)) {
            wrapper.eq("pests_type",pestsType);
        }
        //排序
        wrapper.orderByDesc("stime");

        //调用方法实现条件查询分页
        pestsControlService.page(pageTeacher,wrapper);
        log.error(pageTeacher.getPages());
        log.error(pageTeacher.getSize());
        long pages = pageTeacher.getPages();
        long size = pageTeacher.getSize();
        log.error(pageTeacher.getCountId());
        log.error(pageTeacher.getMaxLimit());

        long total = pageTeacher.getTotal();//总记录数
        List<PestsControl> records = pageTeacher.getRecords(); //数据list集合
        List<PestsControlVo> record = new ArrayList<>();
        for (PestsControl pc :
                records) {
            PestsControlVo vo = new PestsControlVo();
            BeanUtil.copyProperties(pc,vo);
            vo.setPestsQrcode(pestsQrcodeService.getByQrcode(pc.getQrcode()));
            vo.setUcenterMember(ucenterMemberService.getById(pc.getUserId()));
            record.add(vo);
        }
        return Result.ok().data("total",total).data("pages",pages).data("size",size).data("rows",record);
    }

    /**
     * 后台管理系统，查看记录时，按code_int 排序进行
     * @param current
     * @param limit
     * @param teacherQuery
     * @return
     */
    @ApiOperation(value = "分页查询")
    @OperLog(type = "分页查询",module = "PestsControlController",requestDes = "分页查询防治的方法")
    @PostMapping("pagePestsAndQrcode/{current}/{limit}")
    public Result pagePestsAndQrcode(@PathVariable long current, @PathVariable long limit,
                       @RequestBody(required = false) PestsControlQuery teacherQuery) {
        //创建page对象
        Page<PestsQrcodeVo> pageTeacher = new Page<>(current,limit);

        //构建条件
        QueryWrapper<PestsControl> wrapper = new QueryWrapper<>();
        // 多条件组合查询
        // mybatis学过 动态sql
        String deviceId = teacherQuery.getDeviceId();
        String begin = teacherQuery.getBegin();
        String end = teacherQuery.getEnd();
        String pestsType = teacherQuery.getPestsType();
        String userId = teacherQuery.getUserId();
        String projectId = teacherQuery.getProjectId();
        //判断条件值是否为空，如果不为空拼接条件
        if(!StringUtils.isEmpty(deviceId)) {
            //构建条件
            wrapper.like("device_id",deviceId);
        }
        if(!StringUtils.isEmpty(begin)) {
            wrapper.ge("c.stime",begin);
        }
        if(!StringUtils.isEmpty(end)) {
            wrapper.le("c.stime",end);
        }
        if(!StringUtils.isEmpty(userId)) {
            wrapper.eq("user_id",userId);
        }
        if(!StringUtils.isEmpty(pestsType)) {
            wrapper.eq("pests_type",pestsType);
        }
        if(!StringUtils.isEmpty(projectId)) {
            wrapper.eq("project_id",projectId);
        }
        //排序
        wrapper.orderByDesc("code_int");
        //调用方法实现条件查询分页
        pestsControlService.pagePestsControlAndQrcode(pageTeacher,wrapper);
        long total = pageTeacher.getTotal();//总记录数
        List<PestsQrcodeVo> records = pageTeacher.getRecords(); //数据list集合
        return Result.ok().data("total",total).data("rows",records);
    }

    //4 条件查询带分页的方法
    @ApiOperation(value = "分页查询")
    @OperLog(type = "分页查询",module = "PestsControlController",requestDes = "分页查询防治的方法")
    @PostMapping("pageControlCondition/{current}/{limit}")
    public Result pageControlCondition(@PathVariable long current, @PathVariable long limit,
                                                          @RequestBody(required = false) PestsControlQuery teacherQuery) {
        //创建page对象
        Page<PestsControl> pageTeacher = new Page<>(current,limit);

        //构建条件
        QueryWrapper<PestsControl> wrapper = new QueryWrapper<>();
        // 多条件组合查询
        // mybatis学过 动态sql
        String deviceId = teacherQuery.getDeviceId();
        String begin = teacherQuery.getBegin();
        String end = teacherQuery.getEnd();
        String pestsType = teacherQuery.getPestsType();
        String userId = teacherQuery.getUserId();
        String projectId = teacherQuery.getProjectId();
        //判断条件值是否为空，如果不为空拼接条件
        if(!StringUtils.isEmpty(projectId)) {
            wrapper.eq("project_id",projectId);
        }
        if(!StringUtils.isEmpty(deviceId)) {
            //构建条件
            wrapper.like("device_id",deviceId);
        }
        if(!StringUtils.isEmpty(begin)) {
            wrapper.ge("stime",begin);
        }
        if(!StringUtils.isEmpty(end)) {
            wrapper.le("stime",end);
        }

        if(!StringUtils.isEmpty(userId)) {
            wrapper.eq("user_id",userId);
        }
        if(!StringUtils.isEmpty(pestsType)) {
            wrapper.eq("pests_type",pestsType);
        }
        //排序
        wrapper.orderByDesc("stime");

        //调用方法实现条件查询分页
        pestsControlService.page(pageTeacher,wrapper);

        long total = pageTeacher.getTotal();//总记录数
        List<PestsControl> records = pageTeacher.getRecords(); //数据list集合
        List<PestsControlVo> record = new ArrayList<>();
        for (PestsControl pc :
                records) {
            PestsControlVo vo = new PestsControlVo();
            BeanUtil.copyProperties(pc,vo);
            vo.setPestsQrcode(pestsQrcodeService.getByQrcode(pc.getQrcode()));
            vo.setUcenterMember(ucenterMemberService.getById(pc.getUserId()));
            record.add(vo);
        }
        return Result.ok().data("total",total).data("rows",record);
    }


    @ApiOperation(value = "添加防治数据")
    @OperLog(type = "增加",module = "PestsControlController",requestDes = "添加防治数据")
    @PostMapping("addPestsControl")
    public Result addPestsControl(@RequestBody PestsControlModel eduTeacher) {
        PestsControl pestsControl = new PestsControl();
        BeanUtils.copyProperties(eduTeacher,pestsControl);
        Date stime = DateUtil.parse(eduTeacher.getStime(), "yyyy-MM-dd HH:mm:ss");
        pestsControl.setStime(stime);

        String str = eduTeacher.getUserId();
        UcenterMember pestsProject = ucenterMemberService.getById(str);
        pestsControl.setProjectId(pestsProject.getProjectId());
        boolean save = pestsControlService.save(pestsControl);
        if(save) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }

    //
    @ApiOperation(value = "查询")
    @OperLog(type = "查询",module = "PestsControlController",requestDes = "查询防治的方法")
    @GetMapping("getDictByName/{name}")
    public Result getDictByName(@PathVariable String name) {
        Result result = dictionaryClient.getByName(name);
        return Result.ok().data("dict",result);
    }
    //根据id进行查询
    @ApiOperation(value = "查询")
    @OperLog(type = "查询",module = "PestsControlController",requestDes = "查询防治的方法")
    @GetMapping("getPestsControl/{id}")
    public Result getPestsControl(@PathVariable String id) {
        PestsControl eduTeacher = pestsControlService.getById(id);
        return Result.ok().data("teacher",eduTeacher);
    }
    //
    @ApiOperation(value = "查询")
    @OperLog(type = "查询",module = "PestsControlController",requestDes = "查询防治的方法")
    @GetMapping("getPestsControlByQrcode/{qrcode}")
    public Result getPestsControlByQrcode(@PathVariable String qrcode) {
        QueryWrapper<PestsControl> wrapper = new QueryWrapper<>();
        wrapper.eq("qrcode",qrcode);
        wrapper.last("LIMIT 1");
        PestsControl eduTeacher = pestsControlService.getOne(wrapper,false);
        return Result.ok().data("teacher",eduTeacher);
    }
    //修改功能
    @ApiOperation(value = "更新")
    @OperLog(type = "更新",module = "PestsControlController",requestDes = "更新防治的方法")
    @PostMapping("updatePestsControl")
    public Result updatePestsControl(@RequestBody PestsControl eduTeacher) {
        boolean flag = pestsControlService.updateById(eduTeacher);
        if(flag) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }
    /**
     *
     * @param day
     * @return
     */
    @ApiOperation(value = "统计")
    @OperLog(type = "统计",module = "PestsControlController",requestDes = "统计防治的方法")
    @GetMapping("countDay/{day}/{projectId}")
    public Result countDay(@PathVariable String day , @PathVariable String projectId) {
        Integer count = pestsControlService.countDayByProjectId(day,projectId);
        return Result.ok().data("countDay",count);
    }
    /**
     *
     * @param day
     * @return
     */
    @ApiOperation(value = "统计")
    @OperLog(type = "统计",module = "PestsControlController",requestDes = "统计防治的方法")
    @GetMapping("countDay/{day}/{projectId}/{memberId}")
    public Result countDay(@PathVariable String day,@PathVariable String projectId,@PathVariable String memberId) {
        Integer count = pestsControlService.countDayByProjectIdAndMemberId(day,projectId,memberId);
        return Result.ok().data("countDay",count);
    }
    /**
     *
     * @param day
     * @return
     */
    @ApiOperation(value = "统计")
    @OperLog(type = "统计",module = "PestsControlController",requestDes = "统计防治的方法")
    @GetMapping("countDay/{day}")
    public Result countDay(@PathVariable String day) {
        Integer count = pestsControlService.countDay(day);
        return Result.ok().data("countDay",count);
    }
    /**
     *  统计某个项目下的Pests记录数
     * @param projectId
     * @return
     */
    @ApiOperation(value = "统计")
    @OperLog(type = "统计",module = "PestsControlController",requestDes = "统计防治的方法")
    @GetMapping("countPestsByProjectId/{projectId}")
    public Result countPestsByProjectId(@PathVariable String projectId) {
        Integer count = pestsControlService.countPestsByProjectId(projectId);
        return Result.ok().data("count",count);
    }


    /**
     *
     * @param
     * @return
     */
    @ApiOperation(value = "统计")
    @OperLog(type = "统计",module = "PestsControlController",requestDes = "统计防治的方法")
    @GetMapping("countPestsAll")
    public Integer countPestsAll() {
        Integer count = pestsControlService.getBaseMapper().selectCount(null);
        return count;
    }

    @ApiOperation(value = "统计")
    @OperLog(type = "统计",module = "PestsControlController",requestDes = "统计防治的方法")
    @PostMapping("statistics")
    public Result getStatistics(@RequestBody(required = false) PestsControlQuery query){

        //构建条件
        QueryWrapper<PestsControl> wrapper = new QueryWrapper<>();
        // 多条件组合查询
        // mybatis学过 动态sql
        String userId = query.getUserId();
        String deviceId = query.getDeviceId();
        String begin = query.getBegin();
        String end = query.getEnd();
        //判断条件值是否为空，如果不为空拼接条件
        if(!StringUtils.isEmpty(deviceId)) {
            //构建条件
            wrapper.like("user_id",userId);
        }
        if(!StringUtils.isEmpty(deviceId)) {
            //构建条件
            wrapper.like("device_id",deviceId);
        }
        if(!StringUtils.isEmpty(begin)) {
            wrapper.ge("stime",begin);
        }
        if(!StringUtils.isEmpty(end)) {
            wrapper.le("stime",end);
        }

        //排序
        wrapper.orderByDesc("id");
        List<PestsControl> pestsControls = pestsControlService.list(wrapper);
        List<Map<String,Integer>> sta = pestsControlService.getStatistics(pestsControls);
        return Result.ok().data("sta",sta);
    }

    /**
     * 根据
     * @param userId
     * @return
     */
    @ApiOperation(value = "统计")
    @OperLog(type = "统计",module = "PestsControlController",requestDes = "统计防治的方法")
    @GetMapping("getPestsControlAndQrcode/{userId}")
    public Result getPestsControlAndQrcode(@PathVariable String userId) {
        List<PestsQrcodeVo> count = pestsControlService.getPestsControlAndQrcode(userId);
        return Result.ok().data("pests",count);
    }
}

